package com.ad.aidai.activitys.main;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.widget.FrameLayout;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseActivity;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.common.ADFragmentManager;
import com.ad.aidai.common.RongImManager;
import com.ad.aidai.common.listener.OnActivityBackPressedListener;
import com.ad.aidai.common.widgets.DragPointView;
import com.ad.aidai.common.widgets.bottombar.BottomBar;
import com.ad.aidai.common.widgets.bottombar.BottomBarTab;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.fragments.me.MeFragment;
import com.ad.aidai.fragments.messagelist.MessageListFragment;
import com.ad.aidai.fragments.order.OrderFragment;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideTopExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 主界面
 * <p>
 * Created by Yusxon on 2016/12/16.
 */

public class MainActivity extends BaseActivity implements IUnReadMessageObserver, DragPointView.OnDragListencer, MainContract.View {

    @BindView(R.id.main_middle)
    FrameLayout mainMiddle;
    @BindView(R.id.bar_bottom)
    BottomBar barBottom;

    private List<FragmentInfo> fragments;
    /**
     * 切换前显示的fragment
     */
    private int lastPosition;
    private FragmentManager mFragmentManager;

    //要显示的fragment
    private FragmentInfo newFragmentInfo;

    private BottomBarTab messageBottomBarTab;

    private Conversation.ConversationType[] mConversationsTypes;

    private LoadingDialog loadingDialog;
    private BaseAnimatorSet mBasIn;
    private BaseAnimatorSet mBasOut;

    private MainContract.Presenter mPresenter;


    class FragmentInfo {
        private String tag;
        private Class<?> clss;
        private Bundle args;
        private BaseFragment fragment;

        FragmentInfo(String _tag, Class<?> _class, Bundle _args) {
            tag = _tag;
            clss = _class;
            args = _args;
        }
    }

    @Override
    protected void initView() {

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        messageBottomBarTab = new BottomBarTab(this, R.mipmap.icon_message_dark);
        barBottom.addItem(new BottomBarTab(this, R.mipmap.icon_order_dark)).
                addItem(messageBottomBarTab).
                addItem(new BottomBarTab(this, R.mipmap.icon_me_dark));
        messageBottomBarTab.setDragListencer(this);
    }

    @Override
    protected void initData() {
        mBasIn = new BounceTopEnter();
        mBasOut = new SlideTopExit();

        new MainPresenter(this, this).subscribe();

        mPresenter.loadData();

        mFragmentManager = getSupportFragmentManager();

        fragments = new ArrayList<>();
        fragments.add(new FragmentInfo("爱代单", OrderFragment.class, null));
        fragments.add(new FragmentInfo("消息", MessageListFragment.class, null));
        fragments.add(new FragmentInfo("我的", MeFragment.class, null));

        barBottom.setOnItemClickListener(new BottomBar.OnItemClickListener() {
            @Override
            public void Click(BottomBarTab tab, int position) {
                toggleFragment(position);
            }
        });

        lastPosition = 0;
        toggleFragment(0);

        mConversationsTypes = new Conversation.ConversationType[]{Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.PUBLIC_SERVICE,
                Conversation.ConversationType.APP_PUBLIC_SERVICE,
                Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.DISCUSSION
        };

        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, mConversationsTypes);
    }

    @Override
    public void setPresenter(MainContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    /**
     * 切换fragment
     *
     * @param position
     */
    private void toggleFragment(int position) {
        if (position >= 0 && position < fragments.size()) {
            //上一个fragment
            FragmentInfo lastFragmentInfo = fragments.get(lastPosition);

            newFragmentInfo = fragments.get(position);
            //隐藏掉上一个fragment
            if (lastFragmentInfo.fragment != null) {
                mFragmentManager.beginTransaction()
                        .hide(fragments.get(lastPosition).fragment)
                        .commit();
            }
            if (newFragmentInfo.fragment == null) {
                newFragmentInfo.fragment = (BaseFragment) Fragment.instantiate(this, newFragmentInfo.clss.getName(),
                        newFragmentInfo.args);
                mFragmentManager.beginTransaction()
                        .add(mainMiddle.getId(), newFragmentInfo.fragment, newFragmentInfo.tag)
                        .commit();
            } else {
                mFragmentManager.beginTransaction()
                        .show(newFragmentInfo.fragment)
                        .commit();
            }
            lastPosition = position;
        }
    }

    @Override
    protected void subscribeEvents() {

    }

    @Override
    public void onCountChanged(int count) {
        Logger.t("MainActivity").i("未读消息数：" + count);
        if (count == 0) {
            messageBottomBarTab.setmUnreadNumViewText("");
        } else if (count > 0 && count < 100) {
            messageBottomBarTab.setmUnreadNumViewText(String.valueOf(count));
        } else {
            messageBottomBarTab.setmUnreadNumViewText("...");
        }
    }

    @Override
    public void onDragOut() {
        RongIM.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                if (conversations != null && conversations.size() > 0) {
                    for (Conversation c : conversations) {
                        RongIM.getInstance().clearMessagesUnreadStatus(c.getConversationType(), c.getTargetId(), null);
                    }
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {

            }
        }, mConversationsTypes);
    }

    @Override
    public void onBackPressed() {
        OnActivityBackPressedListener listener = ADFragmentManager.getTopListener();
        if (listener == null || listener.onActivityBackPressed()) {
            RongImManager.exit();
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        RongIM.getInstance().removeUnReadMessageCountChangedObserver(this);
        super.onDestroy();
    }

    @Override
    public void showUpdateDialog(String version, String updateMessage) {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.title("检测到最新版本: " + version)
                .titleTextSize(18)
                .content(updateMessage)
                .btnText("稍后更新", "立即更新")
                .showAnim(mBasIn)
                .dismissAnim(mBasOut)
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mPresenter.updateApp();
                        dialog.dismiss();
                    }
                });
    }
}
